package com.googlecode.javatools.classparser.impl;

import java.io.DataInput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.googlecode.javatools.classparser.AttributeInfoParser;
import com.googlecode.javatools.classparser.types.AttributeInfo;
import com.googlecode.javatools.classparser.types.ConstantEntry;
import com.googlecode.javatools.classparser.types.ConstantPool;
import com.googlecode.javatools.classparser.types.impl.AttributeInfoImpl;

public class AttributeInfoParserImpl implements AttributeInfoParser
{
	public Collection<AttributeInfo> parse(final DataInput in, final ConstantPool constantPool) throws IOException
	{
		final List<AttributeInfo> attributesList = new ArrayList<AttributeInfo>();

		final int attributesCount = in.readUnsignedShort();
		for (int a = 0; a < attributesCount; a++)
		{
			final AttributeInfo attribute = parseAttribute(in, constantPool);
			attributesList.add(attribute);
		}

		return attributesList;
	}

	private AttributeInfo parseAttribute(final DataInput in, final ConstantPool constantPool) throws IOException
	{

		final int nameIndex = in.readUnsignedShort();
		if (nameIndex != -1)
		{
			final ConstantEntry entry = constantPool.entryAt(nameIndex);

			final int attributeLength = in.readInt();
			final byte[] value = new byte[attributeLength];
			for (int b = 0; b < attributeLength; b++)
			{
				value[b] = in.readByte();
			}

			return new AttributeInfoImpl(entry.toUTF8(), value);
		}

		throw new IllegalStateException("nameIdex is invalid for attribute");
	}

}
